package com.jiamao.goplay.ui.discover;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.OrientationHelper;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.jiamao.goplay.BR;
import com.jiamao.goplay.R;
import com.jiamao.goplay.adapter.FindAdapter;
import com.jiamao.goplay.app.AppViewModelFactory;
import com.jiamao.goplay.base.BaseMVVMFragment;
import com.jiamao.goplay.config.Config;
import com.jiamao.goplay.databinding.DiscoverFindLayoutBinding;
import com.jiamao.goplay.ui.discover.vm.FindVM;
import com.jiamao.goplay.view.DouYinLayoutManager;
import com.jiamao.goplay.view.EmptyCallback;
import com.jiamao.goplay.view.FindEmptyCallback;
import com.jiamao.goplay.view.LoadingCallback;
import com.jiamao.goplay.view.LocationErrorCallback;
import com.jiamao.goplay.view.TimeoutCallback;
import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.callback.SuccessCallback;
import com.kingja.loadsir.core.Convertor;
import com.kingja.loadsir.core.LoadService;
import com.kingja.loadsir.core.LoadSir;
import com.netease.nim.uikit.api.NimUIKit;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import me.goldze.mvvmhabit.bus.Messenger;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.SPUtils;

/**
 * 发现
 */
public class FindFragment extends BaseMVVMFragment<DiscoverFindLayoutBinding, FindVM> {
    private LoadService loadService;
    private static final String[] CHANNELS = new String[]{"附近", "发现"};
    private List<String> mDataList = Arrays.asList(CHANNELS);
    private List<Fragment> fragmentList = new ArrayList();

    private int sex = 0 ;

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }


    @Override
    public FindVM initViewModel() {
        //使用自定义的ViewModelFactory来创建ViewModel，如果不重写该方法，则默认会调用LoginViewModel(@NonNull Application application)构造方法
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getActivity().getApplication());
        return ViewModelProviders.of(this, factory).get(FindVM.class);
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, initContentView(inflater, container, savedInstanceState), container, false);
        //第二步：注册布局View
        loadService = LoadSir.getDefault().register(binding.getRoot(), new Callback.OnReloadListener() {
            @Override
            public void onReload(View v) {
                KLog.d("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+v.getId());
                if (v.getId() == R.id.ll_location_error){
                    Messenger.getDefault().send(1, Config.MGER_LOCATION_TYPE_RECY);
                }else  if (v.getId() == R.id.ll_find_nodata){
                    viewModel.getLoadInitData();
                }else {
                    viewModel.getLoadInitData();
                }
                // 重新加载逻辑
            }
        },new Convertor<Integer>() {
            @Override
            public Class<? extends Callback> map(Integer httpResult) {
                Class<? extends Callback> resultCode = SuccessCallback.class;

                switch (httpResult) {
                    case 0://成功回调
                        resultCode = SuccessCallback.class;
                        break;
                    case 1://成功回调
                        resultCode = LoadingCallback.class;
                        break;
                    case 2://成功回调
                        resultCode = TimeoutCallback.class;
                        break;
                    case 3://成功回调
                        resultCode = FindEmptyCallback.class;
                        break;
                    case 4:
                        resultCode = LocationErrorCallback.class;
                        break;
                }
                Log.d("HTML","resultCode: "+resultCode+" httpResult:"+httpResult);
                return resultCode;
            }
        });

        return loadService.getLoadLayout();
    }


    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.discover_find_layout;
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        viewModel.uc.pSwitchEvent.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(@Nullable Integer aBoolean) {
                //pSwitchObservable是boolean类型的观察者,所以可以直接使用它的值改变密码开关的图标
                binding.listview.smoothScrollToPosition(aBoolean+1);
            }
        });

        viewModel.uc.uiInitRefreshEvent.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(@Nullable Integer aBoolean) {
                //pSwitchObservable是boolean类型的观察者,所以可以直接使用它的值改变密码开关的图标
                loadService.showWithConvertor(aBoolean);
            }
        });
        viewModel.uc.refreshEvent.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(@Nullable Integer aBoolean) {
                binding.refreshLayout.finishRefresh();
                binding.refreshLayout.finishLoadMore();
            }
        });
        viewModel.uc.startChat.observe(this, new Observer<String>() {
            @Override
            public void onChanged(@Nullable String aBoolean) {

                NimUIKit.startP2PSession(getActivity(),aBoolean);
            }
        });




    }

    @Override
    public void initData() {
        super.initData();
        sex = SPUtils.getInstance().getInt(Config.SEX);
        int pz = SPUtils.getInstance().getInt("pz",-1);

        if (pz==-1){
            if (sex == 0){
                sex = 1;
            }else {
                sex = 2;
            }
        }
        else if (pz == 1){
            sex = 1 ;
        }else if(pz ==2){
            sex = 2 ;
        }
        else  {
            sex = 0 ;
        }

        viewModel.sex = sex;
        binding.refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                viewModel.getLoadData(0);
            }
        });
        binding.refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                viewModel.getLoadData(1);
            }
        });
        binding.setAdapter(new FindAdapter(getContext()));
        DouYinLayoutManager douYinLayoutManager = new DouYinLayoutManager(getContext(), OrientationHelper.VERTICAL,false){

        };
        RecyclerView recyclerView = binding.getRoot().findViewById(R.id.listview);
        recyclerView.setLayoutManager(douYinLayoutManager);

        douYinLayoutManager.setonViewPagerListener(new DouYinLayoutManager.onViewPagerListener() {
            @Override
            public void onPageSelected(boolean isfa, View spanVie) {

               int pos =  recyclerView.getChildAdapterPosition(spanVie);
               viewModel.addlookeduser(pos);
                KLog.d("pos :"+pos+" position:"+pos);
            }

            @Override
            public void smoothScrollToPosition(int position) {

            }
        });
//        douYinLayoutManager.set
      //  viewModel.getLoadInitData();
//        binding.refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
//            @Override
//            public void onRefresh() {
//                binding.refresh.setRefreshing(false);
//            }
//        });
    }

    private void goIntentSetting() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getContext().getPackageName(), null);
        intent.setData(uri);
        try {
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setSex(int sex){
        viewModel.sex = sex;
        viewModel.getLoadData(0);
    }
}
